#!/bin/bash

# Test runner script for Crawl4AI Backend

set -e

echo "🧪 Running Crawl4AI Backend Tests"
echo "=================================="

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if virtual environment is activated
if [[ "$VIRTUAL_ENV" == "" ]]; then
    print_warning "Virtual environment not detected. Consider activating one."
fi

# Install test dependencies if not already installed
print_status "Installing test dependencies..."
pip install -q pytest pytest-asyncio pytest-cov httpx

# Set test environment variables
export TESTING=true
export DATABASE_URL="sqlite+aiosqlite:///:memory:"
export SECRET_KEY="test-secret-key"
export DEBUG=true

# Create test directories
mkdir -p logs
mkdir -p htmlcov

# Run different test suites based on argument
case "${1:-all}" in
    "unit")
        print_status "Running unit tests only..."
        pytest tests/ -m "unit" -v
        ;;
    "integration")
        print_status "Running integration tests only..."
        pytest tests/ -m "integration" -v
        ;;
    "auth")
        print_status "Running authentication tests..."
        pytest tests/test_auth.py -v
        ;;
    "tasks")
        print_status "Running task management tests..."
        pytest tests/test_tasks.py -v
        ;;
    "coverage")
        print_status "Running tests with coverage report..."
        pytest tests/ --cov=app --cov-report=html --cov-report=term-missing
        print_status "Coverage report generated in htmlcov/index.html"
        ;;
    "fast")
        print_status "Running fast tests only (excluding slow tests)..."
        pytest tests/ -m "not slow" -v
        ;;
    "all"|*)
        print_status "Running all tests..."
        pytest tests/ -v
        ;;
esac

# Check test results
if [ $? -eq 0 ]; then
    print_status "✅ All tests passed!"
else
    print_error "❌ Some tests failed!"
    exit 1
fi

# Optional: Run linting and formatting checks
if command -v black &> /dev/null; then
    print_status "Running code formatting check..."
    black --check app/ tests/ || print_warning "Code formatting issues found. Run 'black app/ tests/' to fix."
fi

if command -v flake8 &> /dev/null; then
    print_status "Running linting check..."
    flake8 app/ tests/ || print_warning "Linting issues found."
fi

print_status "Test run completed!"
